//
//  M4BankNameListViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/14.
//

import UIKit
import KakaJSON

class M4BankNameListViewController: M4BaseViewController {
    
    lazy var searchView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    lazy var searchIcon: UIImageView = {
        let icon = UIImageView()
        icon.image = UIImage(named: "info_icon_search")
        return icon
    }()
    
    lazy var searchTF: UITextField = {
        let tf = UITextField()
        let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), .foregroundColor: COLOR_666666]
        tf.attributedPlaceholder = NSAttributedString(string: "Introduzca el nombre del banco para buscar", attributes: attributes)
        tf.textColor = COLOR_333333
        tf.font = UIFont.systemFont(ofSize: 14, weight: .bold)
        tf.borderStyle = .none
        tf.delegate = self
        tf.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
        return tf
    }()
    
    private var allBankName: [String] = []
    
    private var hotBankName: [String] = []
    
    private var M4NameSortKey: [String] = []
    
    private var M4BankNameList: [String : [String]] = [:]
    
    var M4BankNameSelectBlock: ((String) -> Void)?

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
        M4NavBarColor = .white
        M4BackIcon = "icon_back_black"
        M4NavTitle(M4Title: "Nombre del banco ", M4NavTitleColor: COLOR_333333)
        M4BankNamesNet()
        m4UpdateUI()
    }
    
    private func m4UpdateUI() {
        view.addSubview(searchView)
        searchView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(M4NavigationFullHeight()+0.5)
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
        }
        searchView.addSubview(searchIcon)
        searchIcon.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.width.height.equalTo(18)
            make.centerY.equalToSuperview()
        }
        searchView.addSubview(searchTF)
        searchTF.snp.makeConstraints { make in
            make.left.equalTo(searchIcon.snp.right).offset(6)
            make.top.bottom.equalToSuperview()
            make.right.equalToSuperview().offset(-15)
        }
        view.addSubview(M4TableView)
        M4TableView.snp.makeConstraints { make in
            make.top.equalTo(searchView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-M4SafeDistanceBottom())
        }
        M4TableView.register(M4BankNameCell.self, forCellReuseIdentifier: "M4BankNameCell")
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return M4NameSortKey.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let key = M4NameSortKey[section]
        return M4BankNameList[key]?.count ?? 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "M4BankNameCell", for: indexPath) as? M4BankNameCell
        let key = M4NameSortKey[indexPath.section]
        let name = M4BankNameList[key]?[indexPath.row]
        cell?.nameLabel.text = name
        cell?.topLine.isHidden = indexPath.row == 0 ? true : false
        return cell ?? UITableViewCell()
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let key = M4NameSortKey[indexPath.section]
        let name = M4BankNameList[key]?[indexPath.row] ?? ""
        M4BankNameSelectBlock?(name)
        self.navigationController?.popViewController(animated: true)
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UIView()
        header.backgroundColor = COLOR_EEEEEE
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = COLOR_666666
        header.addSubview(label)
        label.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.centerY.equalToSuperview()
        }
        label.text = M4NameSortKey[section]
        return header
    }

    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
}

extension M4BankNameListViewController: UITextFieldDelegate {
    
    @objc func textFieldDidChange(_ textField: UITextField) {
        let string = textField.text ?? ""
        var nameStrs: [String] = []
        for name in allBankName {
            if name.lowercased().contains(string.lowercased()) {
                nameStrs.append(name)
            }
        }
        if string.count == 0 {
            nameStrs = allBankName
        }
        M4SortBankName(bank: nameStrs)
        M4TableView.reloadData()
    }
    
    private func M4BankNamesNet() {
        let param1: [String : Any] = ["VLeBITEHKO": "ESP", "NGgVNDj": M4UserDataManager.m4UserShare.M4Itemcode, "BrCUsPDbc": M4UserDataManager.m4UserShare.M4ProductCode, "GJCurOe": M4UserDataManager.m4UserShare.M4Token]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4bankNames, .post, params: param1)) { model in
            if model.code == 1 {
                let data = model.data as? [String : Any]
                self.allBankName = data?["IYGmOp"] as? [String] ?? []
                self.hotBankName = data?["jOpsqts"] as? [String] ?? []
                self.M4SortBankName(bank: self.allBankName)
                self.M4TableView.reloadData()
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
    
    private func M4SortBankName(bank: [String]) {
        M4NameSortKey.removeAll()
        M4BankNameList.removeAll()
        for name in bank {
            let firstLetter = (name as NSString).substring(with: NSRange.init(location: 0, length: 1)).uppercased()
            var bankNames:[String] = []
            if M4BankNameList.keys.contains(firstLetter) {
                bankNames = M4BankNameList[firstLetter]!
                bankNames.append(name)
            } else {
                bankNames.append(name)
            }
            M4BankNameList[firstLetter] = bankNames
        }
        M4NameSortKey = M4BankNameList.keys.sorted(by: { name1, name2 in
            return name1 < name2
        })
        if hotBankName.count > 0 {
            M4NameSortKey.insert("Bancos populares", at: 0)
            M4BankNameList["Bancos populares"] = hotBankName
        }
    }
}

class M4BankNameCell: M4BaseTableViewCell {
    
    lazy var topLine: UIView = {
        let line = UIView()
        line.backgroundColor = COLOR_EEEEEE
        return line
    }()
    
    lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.textColor = COLOR_333333
        label.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        return label
    }()
    
    override func setViewsLayout() {
        contentView.addSubview(topLine)
        topLine.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview()
            make.height.equalTo(0.5)
        }
        contentView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(20)
            make.bottom.equalToSuperview().offset(-20)
        }
    }
    
    override func M4CellLeftRightEdge() -> CGFloat {
        return 0
    }
    
}

